// 高级性能优化工具
export class AdvancedOptimizer {
  constructor() {
    this.imageCache = new Map();
    this.preloadQueue = [];
    this.performanceMetrics = {};
    this.optimizationLevel = 'high';
  }

  // 智能图片预加载
  async smartPreload(images, priority = 'medium') {
    const priorityMap = {
      critical: 1,
      high: 2,
      medium: 3,
      low: 4
    };

    const sortedImages = images.sort((a, b) => {
      return priorityMap[a.priority || priority] - priorityMap[b.priority || priority];
    });

    // 使用 requestIdleCallback 在空闲时间预加载
    if ('requestIdleCallback' in window) {
      requestIdleCallback(() => {
        this.preloadImages(sortedImages);
      }, { timeout: 2000 });
    } else {
      // 降级处理
      setTimeout(() => {
        this.preloadImages(sortedImages);
      }, 100);
    }
  }

  // 图片压缩检测和优化建议
  analyzeImageOptimization() {
    const images = document.querySelectorAll('img');
    const analysis = {
      oversized: [],
      unoptimized: [],
      suggestions: []
    };

    images.forEach(img => {
      const rect = img.getBoundingClientRect();
      const displaySize = rect.width * rect.height;
      const naturalSize = img.naturalWidth * img.naturalHeight;

      // 检测过大图片
      if (naturalSize > displaySize * 4) {
        analysis.oversized.push({
          element: img,
          displaySize,
          naturalSize,
          ratio: naturalSize / displaySize
        });
      }

      // 检测未优化的图片
      if (img.src.includes('.jpg') && !img.src.includes('webp')) {
        analysis.unoptimized.push({
          element: img,
          currentFormat: 'jpg',
          suggestedFormat: 'webp'
        });
      }
    });

    return analysis;
  }

  // 内存使用优化
  optimizeMemoryUsage() {
    // 清理长时间未使用的缓存
    const now = Date.now();
    const maxAge = 5 * 60 * 1000; // 5分钟

    for (const [key, value] of this.imageCache.entries()) {
      if (now - value.timestamp > maxAge) {
        this.imageCache.delete(key);
      }
    }

    // 强制垃圾回收（如果支持）
    if (window.gc) {
      window.gc();
    }
  }

  // 网络状态自适应优化
  adaptiveOptimization() {
    if ('connection' in navigator) {
      const connection = navigator.connection;

      if (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g') {
        this.optimizationLevel = 'minimal';
        this.enableMinimalMode();
      } else if (connection.effectiveType === '3g') {
        this.optimizationLevel = 'standard';
        this.enableStandardMode();
      } else {
        this.optimizationLevel = 'high';
        this.enableHighPerformanceMode();
      }
    }
  }

  // 最小化模式
  enableMinimalMode() {
    // 禁用非关键功能
    document.querySelectorAll('.non-critical').forEach(el => {
      el.style.display = 'none';
    });

    // 减少动画
    document.body.style.setProperty('--animation-duration', '0.1s');
  }

  // 标准模式
  enableStandardMode() {
    // 启用基本功能
    document.querySelectorAll('.non-critical').forEach(el => {
      el.style.display = '';
    });

    // 标准动画
    document.body.style.setProperty('--animation-duration', '0.2s');
  }

  // 高性能模式
  enableHighPerformanceMode() {
    // 启用所有功能
    document.querySelectorAll('.non-critical').forEach(el => {
      el.style.display = '';
    });

    // 流畅动画
    document.body.style.setProperty('--animation-duration', '0.3s');

    // 预加载更多资源
    this.preloadCriticalResources();
  }

  // 关键资源预加载
  preloadCriticalResources() {
    const criticalResources = [
      // 添加关键资源
    ];

    criticalResources.forEach(resource => {
      const link = document.createElement('link');
      link.rel = 'preload';
      link.href = resource;
      link.as = 'image';
      document.head.appendChild(link);
    });
  }

  // 性能监控和分析
  startAdvancedMonitoring() {
    // 监控关键性能指标
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        list.getEntries().forEach((entry) => {
          this.performanceMetrics[entry.name] = entry.duration;

          // 检测性能问题
          if (entry.duration > 1000) {
            console.warn(`性能警告: ${entry.name} 耗时 ${entry.duration}ms`);
          }
        });
      });

      observer.observe({ entryTypes: ['measure', 'navigation', 'resource'] });
    }

    // 监控内存使用
    if ('memory' in performance) {
      setInterval(() => {
        const memory = performance.memory;
        if (memory.usedJSHeapSize > memory.jsHeapSizeLimit * 0.8) {
          console.warn('内存使用过高，建议清理缓存');
          this.optimizeMemoryUsage();
        }
      }, 30000); // 每30秒检查一次
    }
  }

  // 图片格式检测和优化
  optimizeImageFormats() {
    const images = document.querySelectorAll('img');

    images.forEach(img => {
      // 检测WebP支持
      if (this.supportsWebP()) {
        const originalSrc = img.src;
        const webpSrc = originalSrc.replace(/\.(jpg|jpeg|png)$/i, '.webp');

        // 创建picture元素
        const picture = document.createElement('picture');
        const webpSource = document.createElement('source');
        webpSource.srcset = webpSrc;
        webpSource.type = 'image/webp';

        picture.appendChild(webpSource);
        picture.appendChild(img.cloneNode(true));

        img.parentNode.replaceChild(picture, img);
      }
    });
  }

  // 检测WebP支持
  supportsWebP() {
    const canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  }

  // 获取性能报告
  getPerformanceReport() {
    return {
      optimizationLevel: this.optimizationLevel,
      performanceMetrics: this.performanceMetrics,
      cacheSize: this.imageCache.size,
      memoryUsage: performance.memory ? {
        used: performance.memory.usedJSHeapSize,
        total: performance.memory.totalJSHeapSize,
        limit: performance.memory.jsHeapSizeLimit
      } : null
    };
  }
}

// 全局高级优化实例
export const advancedOptimizer = new AdvancedOptimizer();

// 自动优化初始化
export function initializeAdvancedOptimization() {
  // 启动高级监控
  advancedOptimizer.startAdvancedMonitoring();

  // 自适应优化
  advancedOptimizer.adaptiveOptimization();

  // 图片格式优化
  advancedOptimizer.optimizeImageFormats();

  // 定期内存优化
  setInterval(() => {
    advancedOptimizer.optimizeMemoryUsage();
  }, 60000); // 每分钟优化一次
}




